#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <sys/wait.h>

#define DEF_PAGER "/bin/more"
#define MAXLINE 4096

int main(int argc, char const *argv[])
{
	int n;
	int fd[2];
	pid_t pid;
	char *pager, *argv0;
	char line[MAXLINE];
	FILE *fp;

	if (argc != 2)
		return -1;

	fp = fopen(argv[1], "r");
	pipe(fd);

	if ((pid=fork()) < 0) {
		printf("fork error: %s\n", strerror(errno));
		return -1;
	}
	else if (pid > 0) {
		close(fd[0]);

		while (fgets(line, MAXLINE, fp) != NULL) {
			n = strlen(line);
			write (fd[1], line, n);
		}

		if (ferror(fp)) {
			printf("ferror\n");
			return -1;
		}

		close(fd[1]);
		if (waitpid(pid, NULL, 0) < 0) {
			printf("waitpid error\n");
			return -1;
		}

		exit(0);
	}
	else {
		close(fd[1]);
		dup2(fd[0], STDIN_FILENO);
		close(fd[0]);

		pager = DEF_PAGER;
		if ((argv0 = strrchr(pager, '/')) != NULL)
			argv0++;
		else
			argv0 = pager;

		if (execl(pager, argv0, (char*)0) < 0) {
			printf("execl error: %s\n", strerror(errno));
			return -1;
		}

	}
	return 0;
}